import {
  View,
  StyleSheet,
  Dimensions,
  BackHandler,
  TouchableOpacity,
} from 'react-native';
import React, {useState, useRef, useEffect} from 'react';
import {WebView} from 'react-native-webview';
import {useNavigation} from '@react-navigation/native';
import NavigationBar from '../../components/NavigationBar';
import ViewUtil from '../../utils/ViewUtil';
import Icon from '@react-native-vector-icons/fontawesome';
const TRENDING_URL = 'https://github.com/';
export default function DetailPage({route}) {
  const {item} = route.params;
  const navigation = useNavigation();
  const webViewRef = useRef();

  const [url, setUrl] = useState(
    // item.html_url || TRENDING_URL + item.full_name,
    'https://www.baidu.com/',
  );
  const [canGoBack, setCanGoBack] = useState(false);

  function fn() {
    onBack();
    return true;
  }

  BackHandler.addEventListener('hardwareBackPress', fn);

  const onFavoriteButtonClick = () => {
    console.log('收藏');
  };

  const onShareClick = () => {
    console.log('分享');
  };

  //右边按钮
  const renderRightButton = () => {
    return (
      <View style={{flexDirection: 'row'}}>
        <TouchableOpacity onPress={onFavoriteButtonClick}>
          <Icon
            name={item.isFavorite ? 'star' : 'star-o'}
            size={20}
            style={{color: 'white', marginRight: 10}}
          />
        </TouchableOpacity>
        {ViewUtil.getShareButton(onShareClick)}
      </View>
    );
  };

  const onNavigationStateChange = navState => {
    setUrl(navState.url);
    setCanGoBack(navState.canGoBack);
  };

  const onBack = () => {
    if (canGoBack) {
      webViewRef.current.goBack();
    } else {
      navigation.goBack();
    }
  };

  return (
    <View style={styles.container}>
      <NavigationBar
        title={item.full_name}
        titleLayoutStyle={
          item.full_name.length > 20 ? {paddingRight: 30} : null
        }
        leftButton={ViewUtil.getLeftBackButton(onBack)}
        statusBarOpts={{barStyle: 'dark-content'}}
        rightButton={renderRightButton()}
      />
      <WebView
        ref={webViewRef}
        startInLoadingState={true}
        source={{uri: url}}
        onNavigationStateChange={onNavigationStateChange}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webView: {
    width: Dimensions.get('window').width,
    height: Dimensions.get('window').height,
  },
});
